<template lang="pug">
.chart(:style='chartStyle')
</template>

<script setup name="Chart">
import * as echarts from 'echarts'
import { nextTick, onBeforeMount, onMounted, getCurrentInstance } from 'vue'
import _ from 'lodash-es'
const props = defineProps({
  options: Object,
  autoResize: {
    type: Boolean,
    default: true
  },
  theme: [String, Object],
  width: Number,
  height: Number
})

const { proxy } = getCurrentInstance()

const chartStyle = computed(() => {
  return props.width || props.height
    ? { height: props.height + 'px', width: props.width + 'px' }
    : { height: '100%', width: '100%' }
})

var chart = null

const draw = () => {
  if (chart) {
    chart.setOption(props.options, { notMerge: true })
  }
}

const resize = () => {
  if (chart) {
    chart.resize({ animation: { duration: 300 } })
  }
}

const debouncedResize = _.debounce(resize, 300, { maxWait: 800 })

watch(props, () => {
  draw()
})

const init = () => {
  if (chart) {
    return
  }
  chart = echarts.init(proxy?.$el, props.theme)
  draw()
}

onMounted(() => {
  nextTick(() => init())
  window.addEventListener('resize', debouncedResize)
})

onBeforeMount(() => {
  chart?.dispose()
  window.removeEventListener('resize', debouncedResize)
})
</script>

